<template>
	<div>
		<Form ref="brandQueryForm" :label-width="80" inline>
			<FormItem label="品牌分类">
				<Cascader :data="queryCatalogData" style="width: 200px;" @on-visible-change='onVisibleChange'
				v-model="condition.catalogIDs" @on-change="onQueryClick" :load-data="loadCatalogData">
				</Cascader>
			</FormItem>
			<FormItem label="中文名称">
				<Input v-model="condition.cname" placeholder="中文名称"></Input>
			</FormItem>
			<FormItem label="英文名称">
				<Input v-model="condition.ename" placeholder="英文名称"></Input>
			</FormItem>
		</Form>
		<div style="margin-bottom: 10px;">
			<Button type="primary" @click="onQueryClick">查询</Button> &nbsp;
			<Button type="success" @click="onAddClick">添加</Button> &nbsp;
			<Button type="error" @click="onDeleteClick">删除</Button>
		</div>

		<Table ref="table" border :columns="columns" :data="data" @on-selection-change='onSelectionChange'></Table>

		<div style="margin: 10px;overflow: hidden">
			<div style="float: right;">
				<Page ref="page" :total="total" @on-change="changePage" show-total></Page>
			</div>
		</div>

		<!--对话框-->
		<Modal ref="brandModal" v-model="show" :title="modalTitle">
			<!--表单-->
			<Form ref="brandForm" :model="formData" :rules="ruleValidate" :label-width="80">
				<FormItem label="分类目录" prop="catalogIDs">
					<Cascader :data="formCatalogData" :load-data="loadCatalogData" @on-change = 'onChangeForCasForm'
					 @on-visible-change='onVisibleChangeForForm' v-model="formData.catalogIDs"></Cascader>
				</FormItem>
				<FormItem prop="id" style="display: none;">
					<Input v-model="formData.id"></Input>
				</FormItem>
				<FormItem label="中文名称" prop="cname">
					<Input v-model="formData.cname"></Input>
				</FormItem>
				<FormItem label="英文名称" prop="ename">
					<Input v-model="formData.ename"></Input>
				</FormItem>
				<FormItem label="logo" prop="logo">
					<Input v-model="formData.logo"></Input>
				</FormItem>
				<FormItem label="url" prop="url">
					<Input v-model="formData.url"></Input>
				</FormItem>
				<FormItem label="原产地" prop="source">
					<Input v-model="formData.source"></Input>
				</FormItem>
				<FormItem label="备注" prop="remark">
					<Input v-model="formData.remark"></Input>
				</FormItem>
				<FormItem label="是否启用" prop="status">
					<Select v-model="formData.status">
						<Option value='1'>是</Option>
						<Option value='0'>否</Option>
					</Select>
				</FormItem>
				<FormItem>
					<Button type="primary" @click="handleSubmit('brandForm',formType)" style="margin-left: 250px">确 定</Button>
					<Button @click="handleReset('brandModal')" style="margin-left: 20px">取 消</Button>
				</FormItem>
			</Form>
		</Modal>
	</div>
</template>
<script>
	import {
		getCatalogByPid
	} from '../../api/catalog.js'
	import {
		formatDate,
		limitText
	} from '../../libs/util.js'
	import {
		treeToCascader
	} from '../../libs/object.convert.js'
	import {getBrandByCondition,	deleteBrandByIds,	addBrand,	getBrandById,	updateBrand} from '../../api/brand.js'

	//选中数据集,当前页码，表单中当前选中的分类名称
	let selections = [],page = 1, selectedCatName = '';

	export default {
		data() {
			return {
				condition: {
					catalogIDs: [],
					cname: '',
					ename: ''
				},
				//记录数
				total: 100,
				//商品品牌数据集
				data: [],
				//查询分类数据
				queryCatalogData: [],
				//列定义
				columns: [{
						type: 'selection',
						width: 60,
						align: 'center'
					},
					{
						title: '编号',
						key: 'id'
					},
					{
						title: '中文名称',
						key: 'cname'
					},
					{
						title: '英文名称',
						key: 'ename'
					},
					{
						title: '分类名称',
						key: 'catName'
					},
					{
						title: '原产地',
						key: 'source'
					}, {
						title: '状态',
						key: 'status',
						render: (h, params) => {
							const row = params.row;
							const color = row.status ? 'green' : 'red';
							const text = row.status ? '启用' : '禁用';

							return h('Tag', {
								props: {
									color: color
								}
							}, text);
						}
					},
					{
						title: '操作',
						key: 'action',
						width: 150,
						align: 'center',
						render: (h, params) => {
							return h('div', [
								h('Button', {
									props: {
										type: 'warning',
										size: 'small'
									},
									on: {
										click: () => {
											console.log("品牌id:" + params.row.id);
											//打开修改窗口
											this.initDialog('update');
											//初始化分类ids信息
											this.formData.catalogIDs = []
											//获取该品牌信息
											getBrandById(params.row.id).then(res => {
												this.formData.id = res.data.data.id
												this.formData.cname = res.data.data.cname
												this.formData.ename = res.data.data.ename
												this.formData.url = res.data.data.url
												this.formData.remark = res.data.data.remark
												this.formData.source = res.data.data.source
												this.formData.status = res.data.data.status
												this.formData.logo = res.data.data.logo
												selectedCatName = res.data.data.catName
											}).catch(error => {
												console.log(error);
											})
										}
									}
								}, '编辑')
							]);
						}
					},
				],

				//对话框是否显示
				show: false,
				//对话框标题
				modalTitle: '',
				//表单类型
				formType: 'add',
				//表单数据集
				formData: {
					id: 0,
					cname: '',
					ename: '',
					catalogIDs: [],
					logo: '',
					url: '',
					remark : '',
					source : '',
					status : 1
				},
				//添加或者修改分类数据
				formCatalogData: [],
				//表单数据验证
				ruleValidate: {
					cname: [{
							required: true,
							whitespace: true,
							message: '中文名称不能为空',
							trigger: 'blur'
						},
						{
							pattern: /^\S*$/,
							message: '中文名称不能包括空字符',
							trigger: 'blur'
						}
					],
					ename: [{
							required: true,
							whitespace: true,
							message: '英文名称不能为空',
							trigger: 'blur'
						}
					],
					status: [{
							required: true,
							whitespace: true,
							message: '状态不能为空',
							trigger: 'blur'
						}
					],
					catalogIDs: [{
						type: 'array',
						required: true,
						message: '分类目录不能为空',
						trigger: 'change'
					}],
				}
			}
		},
		methods: {
			load(condition) {
				getBrandByCondition(condition).then(res => {
					this.data = res.data.data.rows;
					this.total = res.data.data.total;
				}).catch(error => {
					console.log(error);
				})
			},
			//通用获取查询条件对象,page为当前页面值
			getCondition(page) {
				let condition = {};
				if (page)
					condition.page = page;
				else {
					condition.page = 1;
				}
				condition.size = 10;
				if (this.condition.catalogIDs.length > 0)
					condition.cid = this.condition.catalogIDs[this.condition.catalogIDs.length - 1];
				condition.cname = this.condition.cname;
				condition.ename = this.condition.ename;
				console.log(condition);
				return condition;
			},
			//查询分类改变事件
			onVisibleChange(e) {
				if (e) {
					console.log('cascader load data..............')
					//异步加载分类数据
					getCatalogByPid(0).then(res => {
						let nodes = []
						if (res.data.data) {
							nodes = treeToCascader(res.data.data);
						}
						console.log(nodes)
						this.queryCatalogData = nodes;
					}).catch(err => {
						console.log(err)
					});
				}
			},
			loadCatalogData(item, callback){
				console.log('load sub catalogs..........')
				item.loading = true;
				//异步加载分类数据
					getCatalogByPid(item.value).then(res => {
						let nodes = []
						if (item.children) {
							nodes = treeToCascader(res.data.data);
							item.children = nodes;
							item.loading = false;
							callback();
						}
						console.log(nodes)
					}).catch(err => {
						console.log(err)
					});
			},

			changePage(e) {
				page = e;
				this.load(this.getCondition(e));
			},
			//单击查询，默认查询首页数据
			onQueryClick() {
				console.log('点击查询。。。');
				this.$nextTick(function() {
					this.$refs.page.currentPage = 1;
					page = 1;
					this.load(this.getCondition());
				})
			},
			//表格选择改变事件
			onSelectionChange(e) {
				console.log(e);
				selections = e;
			},
			//删除按钮
			onDeleteClick() {
				//获取表格选中的数据
				if (selections.length < 1) {
					this.$Message.error('您没有选择数据');
				} else {
					let ids = '';
					for (let i in selections) {
						ids += selections[i].id + ',';
					}
					//确认删除
					this.$Modal.confirm({
						title: '删除提醒',
						content: '<p>您确定要删除编号为【' + ids + '】品牌吗？</p>',
						onOk: () => {
							//根据id删除类型
							deleteBrandByIds({'ids':ids}).then(res => {
								if (res.data.status.code == 2000) {
									this.$Message.success('删除成功!');
								} else {
									this.$Message.error('删除失败!');
								}
								//重新加载当前页
								this.load(this.getCondition(page));
								//清空选择项
								selections = [];
							}).catch(err => {
								console.log(err);
							});
						}
					});
				}
			},
			//表单分类改变事件
			onVisibleChangeForForm(e) {
				console.log(e)
				if (e) {
					//异步加载分类数据
					getCatalogByPid(0).then(res => {
						let nodes = []
						if (res.data.data) {
							nodes = treeToCascader(res.data.data);
						}
						console.log(nodes)
						this.formCatalogData = nodes;
					}).catch(err => {
						console.log(err)
					});
				}
			},
		//表单分类选择改变事件，记录当前被选中的分类名称
		onChangeForCasForm(value, selectedData){
			//获取catName
			console.log("selectedData : "+selectedData[0])
			console.log("selectedData : "+selectedData[0].label)

			selectedCatName = selectedData[selectedData.length - 1].label
		},
			//添加品牌
			onAddClick() {
				//初始化表单数据
				this.formCatalogData = [];
				this.formData = {
					id: 0,
					cname: '',
					ename: '',
					catalogIDs: [],
					logo: '',
					url: '',
					remark : '',
					source : '',
					status : 1
				};
				selectedCatName = '';
				//打开添加窗口
				this.initDialog('add');
			},

			//初始化窗口
			initDialog(type) {
				//显示
				this.show = true;
				//初始化对话框，异步刷新dom
				this.$nextTick(function() {
					//引用技术，方便父组件根据名称访问子组件
					console.log(this.$refs.brandModal);
					//隐藏底部对话框
					this.$refs["brandModal"].footerHide = true;
				});
				if (type == 'add') {
					//弹出添加商品分类的界面
					this.modalTitle = '添加品牌';
					this.formType = 'add';
				} else if (type == 'update') {
					this.modalTitle = '修改品牌';
					this.formType = 'update';
				}
			},
			//提交表单
			handleSubmit(name) {
				this.$refs[name].validate((valid) => {
					if (valid) {
						this.$Message.success('验证成功!');
						if (this.formType == 'add') {
							console.log('add brand..........');
							let brand = {
									cname: this.formData.cname,
									ename: this.formData.ename,
									cid: this.formData.catalogIDs[this.formData.catalogIDs.length - 1],
									catName: selectedCatName,
									url: this.formData.url,
									logo: this.formData.logo,
									remark: this.formData.remark,
									source: this.formData.source,
									status: this.formData.status == 1 ? true : false};
							addBrand(brand).then(res => {
									if (res.data.status.code == 2000) {
										this.$Message.success('添加品牌成功!');
									} else {
										this.$Message.error('添加品牌失败!');
									}
								}).catch(function(error) {
									console.log(error);
								});

						} else if (this.formType == 'update') {
							console.log('update 品牌...........');
							//修改品牌
							updateBrand({
									id: this.formData.id,
									cname: this.formData.cname,
									ename: this.formData.ename,
									cid: this.formData.catalogIDs[this.formData.catalogIDs.length - 1],
									catName: selectedCatName,
									url: this.formData.url,
									logo: this.formData.logo,
									remark: this.formData.remark,
									source: this.formData.source,
									status: this.formData.status == 1 ? true : false}).then(res => {
									if (res.data.status.code == 2000) {
										this.$Message.success('修改品牌成功!');
									} else {
										this.$Message.error('修改品牌失败!');
									}
								}).catch(function(error) {
									console.log(error);
								});
						}
					} else {
						this.$Message.error('表单数据不合法!');
					}
				})
			},
			//重置表单
			handleReset(name) {
				//this.$refs[name].resetFields();
				//全局关闭对话框方法，好像不灵哎！
				//this.$Modal.remove();
				this.show = false;
			}
		},
		mounted: function() {
			this.load({
				page: 1,
				size: 10
			});
			/* this.$nextTick(function(){

			}) */
		}
	}
</script>

<style>
</style>
